package com.region.integral.common_user.obtain.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.common_user.obtain.dao.IKCurrencyBuyGoods;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.common_user.pojo.KCurrencyEntity;
import com.region.integral.common_user.xml.Regulation;
import com.region.integral.common_user.xml.dto.BuyGoods;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.CommonUserLogUtil;
import com.region.integral.util.XMLRegulationUtil;
@Component("ikCurrencyBuyGoods")
public class KCurrencyBuyGoodsImpl extends BaseHibernate implements IKCurrencyBuyGoods{
	@Override
	public void byGoods(int userid, double price, IntegralData integralData) throws IntegralException {
		KCurrencyEntity kcEntity = getKCurrencyEntity(userid);
		if (kcEntity != null) {
			
			Regulation regulation = XMLRegulationUtil.unmarshaller();
			List<BuyGoods> buyGoods = regulation.getBuygoods();
			for (BuyGoods bGoods : buyGoods) {
				if(price!=0 && bGoods.getRate()!=0){
					int mode = (int)(price / bGoods.getRate());
					System.out.println(mode);
					if(mode!=0){
						int currk = kcEntity.getKcurrency();
						int maxKCurrency = kcEntity.getMaxKCurrency();
						int totalk = currk+ (mode*bGoods.getkCurrency());
						kcEntity.setKcurrency(totalk);
						if (maxKCurrency < totalk) {
							kcEntity.setMaxKCurrency(totalk);
						}
						integralData.setSuccee(true);
						hibernateTemplate.update(kcEntity);
						hibernateTemplate.save(CommonUserLogUtil.log(userid, (mode*bGoods.getkCurrency()), "byGoods"));
					}
				}
				if(price!=0 && bGoods.getOver()!=0 && price >= bGoods.getOver()){
					int currk = kcEntity.getKcurrency();
					int totalk = currk+ bGoods.getkCurrency();
					int maxKCurrency = kcEntity.getMaxKCurrency();
					kcEntity.setKcurrency(totalk);
					if (maxKCurrency < totalk) {
						kcEntity.setMaxKCurrency(totalk);
					}
					integralData.setSuccee(true);
					hibernateTemplate.update(kcEntity);
					hibernateTemplate.save(CommonUserLogUtil.log(userid, bGoods.getkCurrency(), "byGoods"));
				}
			}
		} 
	}
}
